import React, { FormEvent } from 'react';
import { Button, Card, DatePicker, Input, message, Modal, Row, Select } from 'antd';

import Form, { FormProps } from 'antd/lib/form';
import './style.less';
import { RouteComponentProps } from 'react-router-dom';
import { queryString } from '../../../../utils';

import { ColorResult, SketchPicker } from 'react-color';
import TextArea from 'antd/lib/input/TextArea';
import { LSUser } from './DouyuPage';
import { getLSUser, updateUser } from './LogService';
import { Hero, queryHeroPage } from '../hero/HeroService';
import UploadImg from '../../../comm/file/UploadImg';

const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';
const confirm = Modal.confirm;

const FormItem = Form.Item;
const Option = Select.Option;


type LSUserFormProps = {} & FormProps & RouteComponentProps;

interface LSUserFormState extends Partial<LSUser> {
  id?: number;
  allHeroList: Hero[]
}

class LSUserFormIndex extends React.Component<LSUserFormProps, LSUserFormState> {
  constructor(props: any) {
    super(props);
    this.state = {
      allHeroList: []
    };
  }

  componentDidMount() {
    var param = queryString();
    const name = param.name;
    this.setState({ name });
    this.initForm(name);

  }

  initForm(name: string) {
    let values: Partial<LSUser> = {};

    name && getLSUser(name!).then(res => {
      if (res.data) {
        values = res.data;
        this.setState({
          ...values
        })
        this.renderForm(values);
      }
    });

    queryHeroPage().then(res => {
      if (res.data) {
        this.setState({
          allHeroList: res.data
        })
        this.renderForm(values);
      }
    });

    this.renderForm(values);
  }


  handleChange(heroCode: string) {
    this.setState({
      heroCode
    })
  }

  renderForm(fieldsValue: Partial<LSUserFormState>) {
    // let color :ColorResult ={
    //   hex: fieldsValue.tagContent,
    // hsl: HSLColor;
    // rgb: RGBColor;
    // }


    // this.setState({ color: (JSON.parse(fieldsValue.tagContent) as ColorResult).rgb })
    // this.setState({imgUrl:})
    this.props.form!.setFieldsValue(fieldsValue, () => {

    });
  }

  formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 8 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 14 },
    },
  };



  handleSubmit = (e: FormEvent) => {
    e.preventDefault();
    const { userPhoto } = this.state;
    this.props.form!.validateFields((err, values) => {
      if (!err) {
        console.log("handleSubmit", values);
        //如果图片无改动，不用再次上传。

        const data: LSUser = {
          ...values,
          userPhoto
        }
        if (values.validTime && values.validTime.length === 2) {

        }

        this.updateLSUser(data);
      };
    });
  };


  onUploadFinishReturn(id: string, name: string, url: string) {
    console.log(id, name, url);
    this.setState({
      userPhoto: url
    })
  }

  onUploadFinish(id: number, name: string) {
    console.log(id, name);
  }

  filterOption() {

  }


  updateLSUser(vo: Partial<LSUser>) {
    updateUser(vo).then(res => {
      if (res.statusCode === '200') {
        this.props.history.goBack();
        message.success("更新成功");
      }
    })
  }


  render() {
    const { form } = this.props;

    const {
      // appCode,
      name, heroName, allHeroList, heroCode, userPhoto
    } = this.state;
    const { getFieldDecorator } = form!;
    console.log("itemFormRender state:", this.state);


    return (
      <div>

        <Card title="编辑">
          <Form onSubmit={this.handleSubmit}>
            <FormItem {...this.formItemLayout} label="昵称">
              {getFieldDecorator('name', {
                rules: [{ required: true, message: '请输入昵称!' }],
              })(<Input style={{ width: "300px" }} placeholder="请输入昵称" />)}
            </FormItem>



            <FormItem {...this.formItemLayout} label="选手头像">
              {/* {getFieldDecorator('userPhoto', {
                rules: [{ message: '请输入!' }],
              })(<Input style={{ width: "300px" }} placeholder="请输入" />)} */}
              <UploadImg
                defaultImgUrl={userPhoto}
                onUploadFinish={this.onUploadFinish.bind(this)}
                onUploadFinishReturn={this.onUploadFinishReturn.bind(this)}
              />

            </FormItem>
            {/*    heroImg: "./././././douyu/h1.png",
        userPhoto: "./././././douyu/tm.jpeg", */}
            {/* <FormItem {...this.formItemLayout} label="英雄">
              {getFieldDecorator('heroImg', {
                rules: [{ message: '请输入!' }],
              })(<Select style={{ width: "300px" }} placeholder="请输入" />)}
            </FormItem> */}

            <FormItem {...this.formItemLayout} label="英雄名称">

              {getFieldDecorator('heroCode', {
                rules: [{ message: '请输入!' }],
              })(<Select
                showSearch
                style={{ width: "300px" }}
                placeholder="请选择选择英雄"
                value={heroCode}
                onChange={this.handleChange.bind(this)}
                filterOption={(input: any, option: any) => {
                  console.log(input, option)

                  return option.key.indexOf(input) !== -1;
                }}
              >
                {allHeroList!.map(vo => {
                  return <Option key={vo.heroName} value={vo.code}>{vo.heroName}</Option>;
                })}
              </Select>)}
            </FormItem>



            <FormItem {...this.formItemLayout} label="血量">
              {getFieldDecorator('v1', {
                rules: [{ required: true, message: '请输入!' }],
              })(<Input style={{ width: "300px" }} placeholder="请输入" />)}
            </FormItem>

            <FormItem {...this.formItemLayout} label="星级">
              {getFieldDecorator('v2', {
                rules: [{ required: true, message: '请输入!' }],
              })(<Input style={{ width: "300px" }} placeholder="请输入" />)}
            </FormItem>

            <FormItem {...this.formItemLayout} label="护甲">
              {getFieldDecorator('v3', {
                rules: [{ required: true, message: '请输入!' }],
              })(<Input style={{ width: "300px" }} placeholder="请输入" />)}
            </FormItem>



            <Row className="submitAction">
              <Button type="primary" htmlType="submit">提交</Button>
              <Button onClick={() => {
                this.props.history.goBack();
              }}
              >取消</Button>
            </Row>
          </Form>
        </Card>
      </div >
    );
  }
}

export default Form.create()(LSUserFormIndex);



